#include "selfinfowidget.h"
#include"model/datacenter.h"
#include<QTimer>
#include<QFileDialog>

SelfInfoWidget::SelfInfoWidget(QWidget *parent)
{
    // 1. 设置基础属性
    this->setFixedSize(450, 250);
    this->setWindowIcon(QIcon(":/images/logo.png"));
    this->setWindowTitle("个⼈信息");

    // 设置关闭后⾃动销毁
    this->setAttribute(Qt::WA_DeleteOnClose);
    // 设置窗⼝显⽰位置为⿏标所在位置.
    this->move(QCursor::pos());
    // 设置背景⾊
    this->setStyleSheet("QWidget { background-color: rgb(255, 255, 255); fontsize: 18px;}\
    QPushButton { border: none; } QPushButton:pressed {background-color: rgb(235, 235, 235);}");

    // 2. 创建界⾯布局
    QHBoxLayout* layout = new QHBoxLayout();
    layout->setContentsMargins(30, 20, 30, 20);
    layout->setSpacing(10);
    this->setLayout(layout);

    // 3. 添加⽤⼾头像
    avatar = new QPushButton();
    avatar->setFixedSize(75, 75);
    avatar->setIconSize(QSize(75, 75));
    avatar->setStyleSheet("QPushButton { border: none; background-color:white; }");
    layout->addWidget(avatar, 0, Qt::AlignTop);

    gridLayout = new QGridLayout();
    gridLayout->setContentsMargins(0, 0, 0, 0);
    gridLayout->setSpacing(10);
    layout->addLayout(gridLayout);

    // 作为下⽅输⼊框的宽度
    QSize size(200, 30);

    // 4.1 ⽤⼾ id (不能编辑, ⽆需切换)
    QLabel* idTag = new QLabel(this);
    idTag->setStyleSheet("QLabel { font-weight: 800; }");
    idTag->setText("序号");
    QLabel* idLabel = new QLabel(this);
    QIcon modifyIcon(":/images/modify.png");
    QIcon submitIcon(":/images/submit.png");

    // 4.2 ⽤⼾昵称
    QLabel* nameTag = new QLabel(this);
    nameTag->setText("昵称");
    nameTag->setStyleSheet("QLabel { font-weight: 800; }");
    nameLabel = new QLabel(this);
    nameLabel->setFixedSize(size);
    nameEdit = new QLineEdit(this);
    nameEdit->setFixedSize(size);
    nameModifyBtn = new QPushButton(this);
    nameModifyBtn->setIcon(modifyIcon);
    nameSubmitBtn = new QPushButton(this);
    nameSubmitBtn->setIcon(submitIcon);
    nameEdit->hide();
    nameSubmitBtn->hide();

    // 4.3 ⽤⼾签名
    QLabel* descTag = new QLabel(this);
    descTag->setText("签名");
    descTag->setStyleSheet("QLabel { font-weight: 800; }");
    descLabel = new QLabel(this);
    descLabel->setFixedSize(size);
    descEdit = new QLineEdit(this);
    descEdit->setFixedSize(size);
    descModifyBtn = new QPushButton(this);
    descModifyBtn->setIcon(modifyIcon);
    descSubmitBtn = new QPushButton(this);
    descSubmitBtn->setIcon(submitIcon);
    descEdit->hide();
    descSubmitBtn->hide();

    // 4.4 ⽤⼾电话
    QLabel* phoneTag = new QLabel(this);
    phoneTag->setText("电话");
    phoneTag->setStyleSheet("QLabel { font-weight: 800; }");
    phoneLabel = new QLabel(this);
    phoneLabel->setFixedSize(size);
    phoneEdit = new QLineEdit(this);
    phoneEdit->setFixedSize(size);
    phoneModifyBtn = new QPushButton(this);
    phoneModifyBtn->setIcon(modifyIcon);
    phoneSubmitBtn = new QPushButton(this);
    phoneSubmitBtn->setIcon(submitIcon);
    phoneEdit->hide();
    phoneSubmitBtn->hide();

    verityCodeEdit = new QLineEdit(this);
    verityCodeEdit->setFixedSize(size);
    verityCodeEdit->setPlaceholderText("验证码");
    verityCodeEdit->hide();
    // 通过这个按钮来显⽰发送间隔时间的倒计时.
    sendVerityCodeBtn = new QPushButton(this);
    sendVerityCodeBtn->setText("获取");
    sendVerityCodeBtn->hide();

#if TEST_UI
    avatar->setIcon(QIcon(":/images/default_avatar.jpg"));
    idLabel->setText("1234");
    nameLabel->setText("张三");
    descLabel->setText("从今天开始认真敲代码");
    phoneLabel->setText("18612345678");
#endif

    // 5. 添加到布局管理器中.
    gridLayout->setRowStretch(0, 1);
    gridLayout->setRowStretch(1, 1);
    gridLayout->setRowStretch(2, 1);
    gridLayout->setRowStretch(3, 1);
    gridLayout->setRowStretch(4, 1);
    gridLayout->addWidget(idTag, 0, 0);
    gridLayout->addWidget(idLabel, 0, 1);
    gridLayout->addWidget(nameTag, 1, 0);
    gridLayout->addWidget(nameLabel, 1, 1);
    gridLayout->addWidget(nameModifyBtn, 1, 2);
    gridLayout->addWidget(descTag, 2, 0);
    gridLayout->addWidget(descLabel, 2, 1);
    gridLayout->addWidget(descModifyBtn, 2, 2);
    gridLayout->addWidget(phoneTag, 3, 0);
    gridLayout->addWidget(phoneLabel, 3, 1);
    gridLayout->addWidget(phoneModifyBtn, 3, 2);
    gridLayout->addWidget(sendVerityCodeBtn, 4, 0);
    gridLayout->addWidget(verityCodeEdit, 4, 1);
    // 6. 设置第⼀⾏的 SizePolicy
    QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
    idTag->setSizePolicy(sizePolicy);
    idLabel->setSizePolicy(sizePolicy);

    //初始化个人数据
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    model::UserInfo* userInfo = dataCenter->getMyselfInfo();
    if(userInfo != nullptr){
        avatar->setIcon(userInfo->avatar);
        idLabel->setText(userInfo->userId);
        nameLabel->setText(userInfo->nickname);
        descLabel->setText(userInfo->description);
        phoneLabel->setText(userInfo->phone);
    }

    initSignalAndSlot();

}

void SelfInfoWidget::initSignalAndSlot()
{
    //修改昵称
    connect(nameModifyBtn, &QPushButton::clicked, this, &SelfInfoWidget::clickNameModifyBtn);
    connect(nameSubmitBtn, &QPushButton::clicked, this, &SelfInfoWidget::clickNameSubmitBtn);

    //修改标签
    connect(descModifyBtn, &QPushButton::clicked, this, &SelfInfoWidget::clickSignatureModifyBtn);
    connect(descSubmitBtn, &QPushButton::clicked, this, &SelfInfoWidget::clickSignatureSubmitBtn);

    //修改电话号码
    connect(phoneModifyBtn, &QPushButton::clicked, this, &SelfInfoWidget::clickPhoneModifyBtn);
    connect(phoneSubmitBtn, &QPushButton::clicked, this, &SelfInfoWidget::clickPhoneSubmitBtn);
    connect(sendVerityCodeBtn, &QPushButton::clicked, this, &SelfInfoWidget::clickSendVerityCodeBtn);

    //修改头像
    connect(avatar, &QPushButton::clicked, this, &SelfInfoWidget::clickAvatar);
}

void SelfInfoWidget::clickNameModifyBtn()
{
    gridLayout->removeWidget(nameLabel);
    nameLabel->hide();
    gridLayout->addWidget(nameEdit, 1, 1);
    nameEdit->show();
    nameEdit->setText(nameLabel->text());
    nameEdit->setFocus();

    // 切换按钮的显⽰
    gridLayout->removeWidget(nameModifyBtn);
    nameModifyBtn->hide();
    gridLayout->addWidget(nameSubmitBtn, 1, 2);
    nameSubmitBtn->show();
}

void SelfInfoWidget::clickNameSubmitBtn()
{
    // 1. 获取到新的名字
    const QString& newName = nameEdit->text();
    if (newName.isEmpty()) {
        return;
    }
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    // 2. 响应结果到了之后, 把界⾯进⾏改变, 恢复成 label 来显⽰
    connect(dataCenter, &model::DataCenter::changeNickNameDone, this, &SelfInfoWidget::clickNameSubmitBtnDone, Qt::UniqueConnection);
    // 3. 发送修改名字请求
    dataCenter->changeNickNameAsync(newName);
}

void SelfInfoWidget::clickNameSubmitBtnDone()
{
    // 隐藏 lineEdit, 显⽰ label
    gridLayout->removeWidget(nameEdit);
    nameEdit->hide();
    gridLayout->addWidget(nameLabel, 1, 1);
    nameLabel->show();

    nameLabel->setText(nameEdit->text());
    // 切换按钮的显⽰
    gridLayout->removeWidget(nameSubmitBtn);
    nameSubmitBtn->hide();
    gridLayout->addWidget(nameModifyBtn, 1, 2);
    nameModifyBtn->show();
}

void SelfInfoWidget::clickSignatureModifyBtn()
{
    // 隐藏 label, 显⽰ lineEdit
    gridLayout->removeWidget(descLabel);
    descLabel->hide();
    gridLayout->addWidget(descEdit, 2, 1);
    descEdit->show();
    descEdit->setText(descLabel->text());
    descEdit->setFocus();
    // 切换按钮的显⽰
    gridLayout->removeWidget(descModifyBtn);
    descModifyBtn->hide();
    gridLayout->addWidget(descSubmitBtn, 2, 2);
    descSubmitBtn->show();
}

void SelfInfoWidget::clickSignatureSubmitBtn()
{
    // 1. 获取到新的签名
    const QString& newDesc = descEdit->text();
    if (newDesc.isEmpty()) {
        return;
    }
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    // 2. 相应结果到了之后, 把界⾯进⾏改变, 恢复成 label 来显⽰
    connect(dataCenter, &model::DataCenter::changeDescriptionDone, this, &SelfInfoWidget::clickSignatureSubmitBtnDone, Qt::UniqueConnection);
    // 3. 发送修改名字请求
    dataCenter->changeDescriptionAsync(newDesc);
}

void SelfInfoWidget::clickSignatureSubmitBtnDone()
{
    // 隐藏 lineEdit, 显⽰ label
    gridLayout->removeWidget(descEdit);
    descEdit->hide();
    gridLayout->addWidget(descLabel, 2, 1);
    descLabel->show();
    descLabel->setText(descEdit->text());

    // 切换按钮的显⽰
    gridLayout->removeWidget(descSubmitBtn);
    descSubmitBtn->hide();
    gridLayout->addWidget(descModifyBtn, 2, 2);
    descModifyBtn->show();
}

void SelfInfoWidget::clickPhoneModifyBtn()
{

    tempPhone = phoneLabel->text();

    // 隐藏 label, 显⽰ lineEdit
    gridLayout->removeWidget(phoneLabel);
    phoneLabel->hide();
    gridLayout->addWidget(phoneEdit, 3, 1);
    phoneEdit->show();
    phoneEdit->setText(phoneLabel->text());
    phoneEdit->setFocus();

    // 切换按钮的显⽰
    gridLayout->removeWidget(phoneModifyBtn);
    phoneModifyBtn->hide();
    gridLayout->addWidget(phoneSubmitBtn, 3, 2);
    phoneSubmitBtn->show();

    // 显⽰验证码输⼊框
    verityCodeEdit->show();
    sendVerityCodeBtn->show();
}

void SelfInfoWidget::clickPhoneSubmitBtn()
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();

    if(tempPhone == phoneEdit->text()){
        clickPhoneSubmitBtnDone();
        return;
    }

    // 判定下 verifyCodeId 是否获取到
    const QString& verifyCodeId = dataCenter->getVerifyCodeId();
    if (verifyCodeId.isEmpty()) {
        LOG() << "验证码尚未获取成功! 稍后再试!";
        return;
    }

    // 获取到验证码输⼊框内容
    const QString& verifyCode = verityCodeEdit->text();
    if (verifyCode.isEmpty()) {
        return;
    }

    // 发送请求. 这⾥的⼿机号码不能从输⼊框读取!
    connect(dataCenter, &model::DataCenter::changePhoneDone, this, &SelfInfoWidget::clickPhoneSubmitBtnDone, Qt::UniqueConnection);
    dataCenter->changePhoneAsync(this->phoneToChange, verifyCodeId, verifyCode);

    // 结束获取按钮的倒计时
    leftTime = 1;
}

void SelfInfoWidget::clickSendVerityCodeBtn()
{
    //将临时号码设置uuid,防止与用户第二次输入一致
    tempPhone = "R" + QUuid::createUuid().toString().sliced(25, 12);;

    // 获取到⼿机号
    const QString& phone = phoneEdit->text();
    if (phone.isEmpty()) {
        return;
    }

    // 记录要绑定的新⼿机号码. 必须在此处记录
    // 使得后续发送修改请求时候的⼿机号码, 和验证的⼿机号码⼀致
    this->phoneToChange = phone;

    // 发送请求
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    dataCenter->getVerifyCodeAsync(phone);

    // 禁⽤发送按钮
    sendVerityCodeBtn->setEnabled(false);

    // 启动定时器, 在⼀定时间之后恢复按钮可⽤.
    leftTime = 30;
    QTimer* timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [=]() {
        if (leftTime <= 1) {
            // 计时结束.
            sendVerityCodeBtn->setEnabled(true);
            sendVerityCodeBtn->setText("获取");
            timer->stop();
            timer->deleteLater();
            return;
        }
        leftTime--;
        sendVerityCodeBtn->setText(QString::number(leftTime) + "s");
    });

    timer->start(1000);

}

void SelfInfoWidget::clickPhoneSubmitBtnDone()
{
    // 隐藏 lineEdit, 显⽰ label
    gridLayout->removeWidget(phoneEdit);
    phoneEdit->hide();
    gridLayout->addWidget(phoneLabel, 3, 1);
    phoneLabel->show();
    if(phoneToChange != ""){
        phoneLabel->setText(phoneToChange);
    }else{
        phoneLabel->setText(phoneEdit->text());
    }
    phoneLabel->setFocus();

    // 切换按钮的显⽰
    gridLayout->removeWidget(phoneSubmitBtn);
    phoneSubmitBtn->hide();

    gridLayout->addWidget(phoneModifyBtn, 3, 2);
    phoneModifyBtn->show();
    // 隐藏验证码输⼊框
    verityCodeEdit->setText("");
    verityCodeEdit->hide();
    sendVerityCodeBtn->hide();
}

void SelfInfoWidget::clickAvatar()
{
    //设置过滤器, 只打开图⽚
    QString filter = "Image files (*.png *.jpeg *.jpg *.bmp)";

    //使用⽂件选择对话框选择图片
    QString imagePath = QFileDialog::getOpenFileName(this, "选择头像", QDir::homePath(), filter);
    if (imagePath.isEmpty()) {
        LOG() << "clickAvatar 未选择图⽚";
        return;
    }

    // 3. 读取图⽚内容
    QByteArray imageBytes = model::loadImageToByteArray(imagePath);

    // 4. 发送请求
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    connect(dataCenter, &model::DataCenter::changeAvatarDone, this, &SelfInfoWidget::clickAvatarDone, Qt::UniqueConnection);
    dataCenter->changeAvatarAsync(imageBytes);
}

void SelfInfoWidget::clickAvatarDone()
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();

    model::UserInfo* myself = dataCenter->getMyselfInfo();
    avatar->setIcon(myself->avatar);
}
